/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hu.bme.j2ee.v37zen.beans;

import hu.bme.j2ee.v37zen.entities.Dial;
import hu.bme.j2ee.v37zen.entities.User;
import java.net.URL;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Kiss Dániel
 */
@Stateless
@LocalBean
public class DialManagerBean {

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    
    @PersistenceContext
    EntityManager em;
    
    @EJB
    CreateDialBean cdb;
    @EJB
    FindUsersBean fub;

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void createAndAddDial(User user, URL url){
        if(user == null || url == null)
        {
            return;
        }
        this.createAndAddDial(user, url, 0);
        
    }
    
    public void createAndAddDial(User user, URL url, int order){
        if(user == null || url == null)
        {
            return;
        }
        Dial dial = cdb.createDial(url, order);
        if(dial == null){
            return;
        }
        user = em.merge(user);
        user.getDials().size();
        user.addDial(dial);
        em.flush();
        //System.out.println(user.toString());
    }
    
    public void removeDial(long id){
        this.removeDial(this.findDialByID(id));
    }
    
    public void removeDial(Dial dial){
        if(dial == null){
            return;
        }
        dial = em.merge(dial);
        User user = fub.findUserByDialID(dial.getId());
        user = fub.findUserByUsernameEager(user.getUsername());
        user.removeDial(dial);
        em.flush();
    }
    
    public void dialDialed(long dialId){
        this.dialDialed(this.findDialByID(dialId));
    }
    
    public void dialDialed(Dial dial){
        if(dial == null){
            return;
        }
        dial = em.merge(dial);
        dial.getHistory().increstTimeOfDialed();
        dial.getHistory().setLastTime(new Date());        
        em.flush();
    }      
    
    @SuppressWarnings("unchecked")
    public Dial findDialByID(long id) {
        Query query = em.createNamedQuery("Dial.findDialByID");
        query.setParameter("id", id);
        List<Dial> list = query.getResultList();
        if(list.isEmpty()){
            return null;
        }
        return list.get(0);
    }
}
